#存放模型

from exts import db
from datetime import datetime
class UserModel(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(100),nullable=False)
    password = db.Column(db.String(200),nullable=False)
    email = db.Column(db.String(100),nullable=False,unique=True)#邮箱唯一
    join_time = db.Column(db.DateTime,default=datetime.now)#用到时调用的是函数而非函数值，不加（）

class EmailCaptchaModel(db.Model):
    __tablename__ = 'email_captcha'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    email = db.Column(db.String(100),nullable=False)
    captcha = db.Column(db.String(100),nullable=False)

class QuestionModel(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(100),nullable=False)
    content = db.Column(db.Text,nullable=False)
    create_time = db.Column(db.DateTime,default=datetime.now)

    #外键
    author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    #反向引用
    author = db.relationship(UserModel,backref=db.backref('questions'))

class AnswerModel(db.Model):
    __tablename__ = 'answer'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    content = db.Column(db.Text,nullable=False)
    create_time = db.Column(db.DateTime,default=datetime.now)

    #回复针对哪个问题以及是有谁发布，需要两个外键
    author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    question_id = db.Column(db.Integer,db.ForeignKey('question.id'))

    #为了操作需要，添加两个关系，用question拿到所有anwser,用author拿到所有answer
    #使用创建时间来排序
    question = db.relationship(QuestionModel,backref=db.backref('answers',order_by=create_time.desc()))
    author = db.relationship(UserModel,backref='answers')
